<?php

namespace app\api\service;

use app\common\model\Category as CategoryModel;
use app\common\exception\BusinessException;
use think\Db;

/**
 * 套餐服务
 */
class Setmeal
{

    /**
     * 条件查询
     *
     * @return array
     */
    public function list($data)
    {
        $result = [];
        // 根据分类id查询套餐
        $category = CategoryModel::get($data['categoryId']);
        if (!$category) {
            // 抛出业务异常
            throw new BusinessException("没有找到对应分类");
        }
        // 获取分类关联套餐
        $setmeals = $category->apiSetmeals()->select();
        if ($setmeals) {
            foreach ($setmeals as $key => $setmeal) {
                $result[] = [
                    'categoryId' => $category->id,
                    'description' => $setmeal->description,
                    'id' => $setmeal->id,
                    'image' => $setmeal->image,
                    'name' => $setmeal->name,
                    'price' => $setmeal->price,
                ];
            }
        }
        return $result;
    }

    /**
     * 根据id查询菜品选项
     *
     * @param int $id
     */
    public function getDishItemById($id)
    {
        $result = [];
        $field = 'sd.copies as copies,d.name as name,d.description as description,d.image as image';
        $list = Db::name('setmeal_dish')
            ->alias('sd')
            ->join('dish d', 'd.id = sd.dish_id')
            ->where('sd.setmeal_id', $id)
            ->field($field)
            ->select();

        if (empty($list)) {
            throw new BusinessException("套餐下没有菜品");
        }

        foreach ($list as $key => $item) {
            $result[] = [
                'copies' => $item['copies'],
                'description' => $item['description'],
                'image' => $item['image'],
                'name' => $item['name'],
            ];
        }

        return $result;
    }
}
